package main

import (
	"os"
	"strings"
	"go/ast"
)

type JunkDrawer struct {
	fname string
	line  int
	doc   []string
	sig   *Sig
	cons  *Contracts
	fd    *ast.FuncDecl
}

type Sig struct {
	name, rcvr  string
	parms, rets []string
}

func scrape(file *File) (funcs []*JunkDrawer, err os.Error) {
	for _, dcl := range file.ast.Decls {
		fd, ok := dcl.(*ast.FuncDecl)
		if !ok {
			continue
		}

		pos := fd.Pos()
		funcs = append(funcs, &JunkDrawer{
			fname: file.name,
			line:  file.fs.File(pos).Line(pos),
			doc:   smoosh_comments(fd.Doc),
			sig:   mksig(fd),
			fd:    fd,
		})
	}

	return funcs, nil
}

func smoosh_comments(cg *ast.CommentGroup) (comments []string) {
	if cg == nil {
		return
	}
	for _, c := range cg.List {
		text := c.Text
		switch text[:2] {
		case "//":
			text = text[2:]
		case "/*":
			text = text[2 : len(text)-2]
		}
		cs := strings.Split(text, "\n")
		comments = append(comments, cs...)
	}
	return
}

//precondition: fd != nil
func mksig(fd *ast.FuncDecl) *Sig {
	r := ""
	if fd.Recv != nil {
		r = fields(fd.Recv)[0]
	}
	return &Sig{
		name:  fd.Name.String(),
		rcvr:  r,
		parms: fields(fd.Type.Params),
		rets:  fields(fd.Type.Results),
	}
}

//postcondition: fl == nil || len(fl.List) == len(out)
func fields(fl *ast.FieldList) (out []string) {
	if fl == nil {
		return
	}
	for _, item := range fl.List {
		for _, nm := range item.Names {
			out = append(out, nm.String())
		}
	}
	return
}
